package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.FlowElementProcessContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.ModelDeploymentContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.CustomPropertiesProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ModelDeploymentPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.StringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ConstanceVariable;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.ModelCustomConfig;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowReModelCustomConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description 保存流程负责人编号配置进程
 * @author liujj
 * @date 2021-10-15
 * @version 1.0
 */
@Component
public class SaveOwnerCodeConfigProcessor implements ModelDeploymentPostProcessor  {

    @Autowired
    private FlowReModelCustomConfigRepository modelCustomConfigRepository;

    @Override
    public void process(ModelDeploymentContext context) {
        saveOwnerCodeConfig(context.getDeployId(), context.getModelJson());
    }

    /**
     * @Description 保存流程负责人名称自定义配置记录
     * @author liujj
     * @date 2021-10-15
     * @param deployId
     * @param modelJson
     */
    private void saveOwnerCodeConfig(String deployId, JsonNode modelJson) {
        ObjectNode properties = (ObjectNode) modelJson.get("properties");
        JsonNode ownerCode = properties.get("ownerCode");
        if (isInvalidConfig(ownerCode)) {
            return;
        }
        JsonNode flowCode = properties.get("process_id");
        if (isInvalidConfig(flowCode)) {
            return;
        }

        ModelCustomConfig modelCustomConfig = new ModelCustomConfig();
        modelCustomConfig.setDeploymentId(deployId);
        modelCustomConfig.setType(ConstanceVariable.OWNER_CODE);
        modelCustomConfig.setConfig(ownerCode.textValue());
        modelCustomConfig.setFlowCode(flowCode.textValue());
        //插入自定义配置
        this.doSaveConfig(modelCustomConfig);
    }

    private boolean isInvalidConfig(JsonNode copierConfigNode) {
        if (Objects.isNull(copierConfigNode) || copierConfigNode.isNull()) {
            return true;
        }
        return false;
    }

    private void doSaveConfig(ModelCustomConfig modelCustomConfig) {
        modelCustomConfigRepository.addModelCustomConfig(modelCustomConfig);
    }
}